Callbacks


A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. Callbacks are used to handle asynchronous operations in JavaScript.

Synchronous Callbacks

Synchronous callbacks are executed immediately within the function that receives them:

function greet(name, callback) {
    console.log("Hello, " + name);
    callback();
}

function sayGoodbye() {
    console.log("Goodbye!");
}

greet("Alice", sayGoodbye); // Outputs: Hello, Alice
                            // Goodbye!

Asynchronous Callbacks

Asynchronous callbacks are often used to continue code execution after an asynchronous operation has completed:

function fetchData(callback) {
    setTimeout(function() {
        console.log("Data fetched");
        callback();
    }, 2000);
}

function processData() {
    console.log("Processing data");
}

fetchData(processData); // Outputs: Data fetched (after 2 seconds)
//          Processing data

Callback Hell

Callback hell refers to the situation where callbacks are nested within other callbacks several levels deep, making the code difficult to read and maintain:

doSomething(function(result) {
    doSomethingElse(result, function(newResult) {
        doAnotherThing(newResult, function(finalResult) {
            console.log(finalResult);
        });
    });
});

For more detailed information, you can check out resources like W3Schools[^1^][1] and MDN Web Docs[^2^][2].